package com.dmzc.stage1.chapter8;

import java.util.LinkedList;

public class LinkedRunnableQueue implements RunnableQueue{

    private final int limit;
    private final DenyPolicy denyPolicy;
    private final LinkedList<Runnable> runnableList=new LinkedList<>();
    private final ThreadPool threadPool;

    public LinkedRunnableQueue(int limit, DenyPolicy denyPolicy, ThreadPool threadPool) {
        this.limit = limit;
        this.denyPolicy = denyPolicy;
        this.threadPool = threadPool;
    }
    /**
     * 当有新的任务进来时首先会offer到队列
     *
     * @param runnable
     */
    @Override
    public void offer(Runnable runnable) {
        synchronized (runnableList){
            if (runnableList.size()>=limit){
                denyPolicy.reject(runnable,threadPool);
            }else{
                runnableList.addLast(runnable);
                runnableList.notifyAll();
            }
        }
    }

    /**
     * 工作线程通过take方法获取Runnable
     *
     * @return
     */
    @Override
    public Runnable take() throws InterruptedException{
        synchronized (runnableList){
            while (runnableList.isEmpty()){
                try{
                    runnableList.wait();
                }catch(InterruptedException e){
                    throw e;
                }
            }
            return runnableList.removeFirst();
        }
    }

    /**
     * 获取任务队列中任务的数量
     *
     * @return
     */
    @Override
    public int size() {
        synchronized(runnableList){
            return runnableList.size();
        }

    }
}
